/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package edu.ccut.saturn.manager.dict.core.dbmanager;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import edu.ccut.saturn.component.SaturnComponentException;
import edu.ccut.saturn.manager.dict.core.Activator;


/**
 * Dom4j Utils
 * 
 * @author LeslieGu
 * 
 */
public abstract class Dom4jUtils {
	private static final String BLANK_STRING = "";

	private static final String POINT = ".";

	private static final String LOG4J_PROPERTIES = "\\WEB-INF\\classes\\log4j.properties";

	private static final String TRUE = "true";

	public static Document getDocment(String file) throws Exception {

		InputStream in = null;
		try {
			in = new FileInputStream(file);
		} catch (Exception e) {
			e.printStackTrace();
			in = Dom4jUtils.class.getResourceAsStream(file);
		}
		if (in == null) {
			throw new SaturnComponentException("Can not find config file.");
		}
		SAXReader reader = new SAXReader();
		Document document = null;
		try {
			document = reader.read(in);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return document;
	}

	public static Document getDocment(InputStream in) throws Exception {

		if (in == null) {
			throw new SaturnComponentException("Can not find config file.");
		}
		SAXReader reader = new SAXReader();
		Document document = null;
		try {
			document = reader.read(in);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return document;
	}

	public static String writeXml(String file, Document doc) {

		String message = null;
		XMLWriter writer = null;
		OutputFormat format = OutputFormat.createPrettyPrint();
		format.setEncoding("GB2312");
		format.setIndent(true);
		format.setIndent(" ");
		format.setNewlines(true);
		OutputStream out = null;
		try {
			out = new FileOutputStream(file);
		} catch (FileNotFoundException e1) {
			try {
				String path = Thread.currentThread().getContextClassLoader()
						.getResource(BLANK_STRING).getFile()
						+ file.substring(1);

				out = new FileOutputStream(path);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
		}
		try {
			writer = new XMLWriter(out, format);
			writer.write(doc);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				writer.close();
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		message = TRUE;
		return message;
	}

	@SuppressWarnings("unchecked")
	public static Element readXmlForElement(String file) throws Exception {

		Document document = null;
		document = Dom4jUtils.getDocment(file);
		if (document == null) {
			throw new SaturnComponentException("Can not create Document.");
		}
		Element root = document.getRootElement();
		if (root == null) {
			throw new SaturnComponentException(
					"The config file don't have element.");

		}
		return root;
	}

	@SuppressWarnings("unchecked")
	public static Properties getPropertiesKey(String file) throws Exception {

		String serverLocation = Activator.getServerLocation();
		Properties properties = new Properties();
		InputStream in = null;
		try {
			in = new FileInputStream(serverLocation + LOG4J_PROPERTIES);
			properties.load(in);
		} catch (Exception e) {
			in = Dom4jUtils.class.getResourceAsStream(file);
		} finally {
			try {
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if (properties.size() <= 0) {
			throw new SaturnComponentException("Can not read properties file.");
		}
		return properties;
	}

	public static String getBeforeStr(String property) {

		String returnStr = BLANK_STRING;
		int secondPos = property.indexOf(POINT, property.indexOf(POINT) + 1);
		if (secondPos > -1) {
			return property.substring(0, secondPos);
		}
		return returnStr;
	}

	public static String getAfterStr(String property) {

		String returnStr = BLANK_STRING;
		int firstPos = property.indexOf(POINT);
		int secondPos = property.indexOf(POINT, property.indexOf(POINT) + 1);
		if (firstPos > -1 && secondPos > -1) {
			return property.substring(secondPos + 1, property.length());
		}
		return returnStr;
	}
}
